/*****************************************************************************
 *
 *  $Id: main.c,v bc2d4bf9cbe5 2012/09/06 18:22:24 fp $
 *
 *  Copyright (C) 2007-2009  Florian Pose, Ingenieurgemeinschaft IgH
 *
 *  This file is part of the IgH EtherCAT Master.
 *
 *  The IgH EtherCAT Master is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License version 2, as
 *  published by the Free Software Foundation.
 *
 *  The IgH EtherCAT Master is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 *  Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with the IgH EtherCAT Master; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *  ---
 *
 *  The license mentioned above concerns the source code only. Using the
 *  EtherCAT technology and brand is only permitted in compliance with the
 *  industrial property and similar rights of Beckhoff Automation GmbH.
 *
 ****************************************************************************/

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <sys/mman.h>
#include <malloc.h>
#include <sched.h>
#include <pthread.h>

#include <QString>
#include <QStringList>

/*****************************preempt****************************************/
#define MY_PRIORITY (49) /* we use 49 as the PRREMPT_RT use 50
                            as the priority of kernel tasklets
                            and interrupt handler by default */

#define MAX_SAFE_STACK (8*1024) /* The maximum stack size which is
                                   guaranteed safe to access without
                                   faulting */
/****************************************************************************/



/****************************************************************************/

#include "ecrt.h"

/****************************************************************************/

// Application parameters
#define FREQUENCY 1000
#define CLOCK_TO_USE CLOCK_REALTIME
//#define MEASURE_TIMING

/****************************************************************************/

#define NSEC_PER_SEC (1000000000L)
#define PERIOD_NS (NSEC_PER_SEC / FREQUENCY)

#define DIFF_NS(A, B) (((B).tv_sec - (A).tv_sec) * NSEC_PER_SEC + \
    (B).tv_nsec - (A).tv_nsec)

#define TIMESPEC2NS(T) ((uint64_t) (T).tv_sec * NSEC_PER_SEC + (T).tv_nsec)

/****************************************************************************/

// EtherCAT
static ec_master_t *master = NULL;
static ec_master_state_t master_state = {};

static ec_domain_t *domain1 = NULL;
static ec_domain_state_t domain1_state = {};

/****************************************************************************/

// process data
static uint8_t *domain1_pd = NULL;

#define SLAVE1  0, 0
#define SLAVE2  0, 1
#define AnaInSlavePos  0, 0
#define AnaOutSlavePos 0, 0

//#define Beckhoff_EK1100 0x16888, 0x26483052
//#define Beckhoff_EL3102 0x16888, 0x26483052
#define Beckhoff_EK1100 0x9, 0x26483052
#define Beckhoff_EL3102 0x9, 0x26483052


// offsets for PDO entries
static int off_dig_out;
static int off_counter_in;
static int off_counter_out;

static unsigned int counter = 0;
static unsigned int blink = 0;
static unsigned int sync_ref_counter = 0;
const struct timespec cycletime = {0, PERIOD_NS};

static int cmd_index_off = 0; //for command line
static int cmd_data_type = 0; //for command line
static int cmd_trigle = 0; //for command line
static int cmd_value = 0; //for command line
static int cmd_slave_num = 0; //for command line

static unsigned int off_table[10][20];

const static ec_pdo_entry_reg_t domain1_regs[] = {

    {SLAVE1,  Beckhoff_EL3102, 0x7010, 1, &off_table[0][0]},
    {SLAVE1,  Beckhoff_EL3102, 0x7010, 2, &off_table[0][1]},
    {SLAVE1,  Beckhoff_EL3102, 0x7010, 3, &off_table[0][2]},
    {SLAVE1,  Beckhoff_EL3102, 0x7010, 4, &off_table[0][3]},
    {SLAVE1,  Beckhoff_EL3102, 0x7010, 5, &off_table[0][4]},

    {SLAVE1,  Beckhoff_EL3102, 0x6000, 1, &off_table[0][5]},
    {SLAVE1,  Beckhoff_EL3102, 0x6000, 2, &off_table[0][6]},
    {SLAVE1,  Beckhoff_EL3102, 0x6000, 3, &off_table[0][7]},
    {SLAVE1,  Beckhoff_EL3102, 0x6000, 4, &off_table[0][8]},
    {SLAVE1,  Beckhoff_EL3102, 0x6000, 5, &off_table[0][9]},
    {}

};

const static ec_pdo_entry_reg_t domain2_regs[] = {
    {SLAVE2, Beckhoff_EL3102, 0x7010, 1, &off_table[1][0]},
    {SLAVE2, Beckhoff_EL3102, 0x6000, 1, &off_table[1][1]},
    {}
};

// DATA in --------------------------

static ec_pdo_entry_info_t el3102_pdo_entries_i[] = {
    {0x6000, 1, 32} //  status
};

// DATA out -------------------------
static ec_pdo_entry_info_t el3102_pdo_entries_o[] = {
    {0x7010, 1, 32} //  status
};


static ec_pdo_info_t el3102_pdos[] = {
    {0x1601, 1, el3102_pdo_entries_o},
    {0x1A00, 1, el3102_pdo_entries_i}
};

static ec_sync_info_t el3102_syncs[] = {
    {2, EC_DIR_OUTPUT, 1,el3102_pdos ,EC_WD_ENABLE},
    {3, EC_DIR_INPUT,  1, el3102_pdos+ 1,EC_WD_ENABLE},
    {0xff}
};


/*****************************************************************************/

struct timespec timespec_add(struct timespec time1, struct timespec time2)
{
    struct timespec result;

    if ((time1.tv_nsec + time2.tv_nsec) >= NSEC_PER_SEC) {
        result.tv_sec = time1.tv_sec + time2.tv_sec + 1;
        result.tv_nsec = time1.tv_nsec + time2.tv_nsec - NSEC_PER_SEC;
    } else {
        result.tv_sec = time1.tv_sec + time2.tv_sec;
        result.tv_nsec = time1.tv_nsec + time2.tv_nsec;
    }

    return result;
}

/*****************************************************************************/


static int domain1_error_count = 0;
void check_domain1_state(void)
{
    ec_domain_state_t ds;

    ecrt_domain_state(domain1, &ds);

    if (ds.working_counter != domain1_state.working_counter) {
        //printf("Domain1: WC %u.\n", ds.working_counter);
        domain1_error_count ++;
    }
    if (ds.wc_state != domain1_state.wc_state) {
        //printf("Domain1: State %u.\n", ds.wc_state);
        domain1_error_count ++;
    }

    domain1_state = ds;
}

/*****************************************************************************/

void check_master_state(void)
{
    ec_master_state_t ms;

    ecrt_master_state(master, &ms);

    if (ms.slaves_responding != master_state.slaves_responding)
        printf("%u slave(s).\n", ms.slaves_responding);
    if (ms.al_states != master_state.al_states)
        printf("AL states: 0x%02X.\n", ms.al_states);
    if (ms.link_up != master_state.link_up)
        printf("Link is %s.\n", ms.link_up ? "up" : "down");

    master_state = ms;
}

/****************************************************************************/

void * cyclic_task(void *)
{

    struct timespec wakeupTime, time;
#ifdef MEASURE_TIMING
    struct timespec startTime, endTime, lastStartTime = {};
    uint32_t period_ns = 0, exec_ns = 0, latency_ns = 0,
             latency_min_ns = 0, latency_max_ns = 0,
             period_min_ns = 0, period_max_ns = 0,
             exec_min_ns = 0, exec_max_ns = 0;
#endif

    // get current time
    clock_gettime(CLOCK_TO_USE, &wakeupTime);

    while(1) {

        wakeupTime = timespec_add(wakeupTime, cycletime);
        clock_nanosleep(CLOCK_TO_USE, TIMER_ABSTIME, &wakeupTime, NULL);

#ifdef MEASURE_TIMING
        clock_gettime(CLOCK_TO_USE, &startTime);
        latency_ns = DIFF_NS(wakeupTime, startTime);
        period_ns = DIFF_NS(lastStartTime, startTime);
        exec_ns = DIFF_NS(lastStartTime, endTime);
        lastStartTime = startTime;

        if (latency_ns > latency_max_ns) {
            latency_max_ns = latency_ns;
        }
        if (latency_ns < latency_min_ns) {
            latency_min_ns = latency_ns;
        }
        if (period_ns > period_max_ns) {
            period_max_ns = period_ns;
        }
        if (period_ns < period_min_ns) {
            period_min_ns = period_ns;
        }
        if (exec_ns > exec_max_ns) {
            exec_max_ns = exec_ns;
        }
        if (exec_ns < exec_min_ns) {
            exec_min_ns = exec_ns;
        }
#endif

        // receive process data
        ecrt_master_receive(master);
        ecrt_domain_process(domain1);

        // check process data state (optional)
        check_domain1_state();

        if (counter) {
            counter--;
        } else { // do this at 1 Hz
            counter = FREQUENCY;

            // check for master state (optional)
            check_master_state();

#ifdef MEASURE_TIMING
            // output timing stats
            printf("period     %10u ... %10u\n",
                    period_min_ns, period_max_ns);
            printf("exec       %10u ... %10u\n",
                    exec_min_ns, exec_max_ns);
            printf("latency    %10u ... %10u\n",
                    latency_min_ns, latency_max_ns);
            period_max_ns = 0;
            period_min_ns = 0xffffffff;
            exec_max_ns = 0;
            exec_min_ns = 0xffffffff;
            latency_max_ns = 0;
            latency_min_ns = 0xffffffff;

    // read process data
    printf("ErrorCount %d   6040 %u 6041 %u 6064 %u \n",domain1_error_count,
            EC_READ_U16(domain1_pd + off_6040),
            EC_READ_U16(domain1_pd + off_6041),
            EC_READ_U32(domain1_pd + off_6064));

#endif

            // calculate new process data
            blink = !blink;
        }

        // write process data
        //EC_WRITE_U8(domain1_pd + off_dig_out, blink ? 0x66 : 0x99);
        //EC_WRITE_U8(domain1_pd + off_counter_out, blink ? 0x00 : 0x02);
        if( cmd_trigle == 1 ) {
            cmd_trigle = 0;
            if(cmd_slave_num <2) {
                if( cmd_data_type == 8) {
                    EC_WRITE_U8(domain1_pd + off_table[cmd_slave_num][cmd_index_off], cmd_value);
                } else if(cmd_data_type == 16 ) {
                    EC_WRITE_U16(domain1_pd + off_table[cmd_slave_num][cmd_index_off], cmd_value);
                } else if(cmd_data_type == 32) {
                    EC_WRITE_U32(domain1_pd + off_table[cmd_slave_num][cmd_index_off], cmd_value);
                }
            }

        }


        // write application time to master

        clock_gettime(CLOCK_TO_USE, &time);
        ecrt_master_application_time(master, TIMESPEC2NS(time));

        if (sync_ref_counter) {
            sync_ref_counter--;
        } else {
            sync_ref_counter = 1; // sync every cycle
            ecrt_master_sync_reference_clock(master);
        }
        ecrt_master_sync_slave_clocks(master);

        // send process data
        ecrt_domain_queue(domain1);
        ecrt_master_send(master);

#ifdef MEASURE_TIMING
        clock_gettime(CLOCK_TO_USE, &endTime);
#endif
    }
}

/****************************************************************************/

int main(int argc, char **argv)
{

    pthread_t thread_id;
    ec_slave_config_t *sc;
    struct sched_param param;

    /* Declare ourself as a real time task */
    param.sched_priority = MY_PRIORITY;
    if(sched_setscheduler(0, SCHED_FIFO, &param) == -1) {
            perror("sched_setscheduler failed");
            exit(-1);
    }

    /* Lock memory */
    if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) {
        perror("mlockall failed");
        return -1;
    }

    master = ecrt_request_master(0);
    if (!master)
        return -1;

    domain1 = ecrt_master_create_domain(master);
    if (!domain1)
        return -1;

    //******************slave 1********************
    // Create configuration for bus coupler
    if (!(sc = ecrt_master_slave_config(master,
                    SLAVE1, Beckhoff_EK1100))) {
        fprintf(stderr, "Failed to get slave configuration.\n");
        return -1;
    }

//    if (ecrt_slave_config_pdos(sc, EC_END, el3102_syncs)) {
//        fprintf(stderr, "Failed to configure PDOs.\n");
//        return -1;
//    }

    if (ecrt_domain_reg_pdo_entry_list(domain1, domain1_regs)) {
        fprintf(stderr, "PDO entry registration failed!\n");
        return -1;
    }


    // configure SYNC signals for this slave
    //ecrt_slave_config_dc(sc, 0x300, 1000000,4400000,0,0);
    ecrt_slave_config_dc(sc, 00, 0,0,0,0);
    //ecrt_slave_config_dc(sc, 0x300, 10000000,5000000,0,0);


    printf("Activating master...\n");
    if (ecrt_master_activate(master))
        return -1;

    // write application time to master
           struct timespec  time;
    clock_gettime(CLOCK_TO_USE, &time);
    ecrt_master_application_time(master, TIMESPEC2NS(time));

    if (!(domain1_pd = ecrt_domain_data(domain1))) {
        return -1;
    }

    printf("Starting cyclic function.\n");
    //cyclic_task();
    int ret = pthread_create(&thread_id,NULL,cyclic_task,NULL);
    if( ret != 0) {
        printf("creating thread faill!.\n");
        return -1;
    }

    char buff[101];
    QString getStr;
    QStringList para;
    bool cov_ok;
    bool trigle;
    while(1) {

        fgets(buff,100,stdin);
        getStr = buff;

        para = getStr.split(" ");

        trigle = true;
        if(para.size() >= 4) {

            cmd_slave_num = para[0].toInt(&cov_ok);
            if( !cov_ok ) trigle = false;
            cmd_index_off = para[1].toInt(&cov_ok);
            if( !cov_ok ) trigle = false;
            cmd_data_type = para[2].toInt(&cov_ok);
            if( !cov_ok ) trigle = false;
            cmd_value = para[3].toInt(&cov_ok,16);
            if( !cov_ok ) trigle = false;

            if( trigle ) {
                cmd_trigle = 1;
            }

        }
        printf("CurrentState : ErrorCount %d \n",domain1_error_count);

        for(int i=0;i<1;i++) {

            printf("slave 7010-1:%X  6000-1:%X        %d %d\n",
                    EC_READ_U32(domain1_pd + off_table[i][0]),
                    EC_READ_U32(domain1_pd + off_table[i][5]) ,off_table[i][0],off_table[i][5]);
            printf("slave 7010-2:%X  6000-2:%X        %d %d\n",
                    EC_READ_U32(domain1_pd + off_table[i][1]),
                    EC_READ_U32(domain1_pd + off_table[i][6]) ,off_table[i][1],off_table[i][6]);
            printf("slave 7010-3:%X  6000-3:%X        %d %d\n",
                    EC_READ_U32(domain1_pd + off_table[i][2]),
                    EC_READ_U32(domain1_pd + off_table[i][7]) ,off_table[i][2],off_table[i][7]);
            printf("slave 7010-4:%X  6000-4:%X        %d %d\n",
                    EC_READ_U32(domain1_pd + off_table[i][3]),
                    EC_READ_U32(domain1_pd + off_table[i][8]) ,off_table[i][3],off_table[i][8]);
            printf("slave 7010-5:%X  6000-5:%X        %d %d\n",
                    EC_READ_U32(domain1_pd + off_table[i][4]),
                    EC_READ_U32(domain1_pd + off_table[i][9]) ,off_table[i][4],off_table[i][9]);

            printf("\n");
        }

        printf("\n\n\n");
    }

    return 0;

}
